<?php

namespace Packages\Log\Repositories;

use Illuminate\Support\Facades\DB;

/**
 * 基础的数据仓库类
 *
 * Class BaseRepository
 * @package App\Repositories
 * @author gl
 */
trait BaseRepository
{

    protected static $db; // 数据库查询实例
    protected static $key = 'guid'; // 搜索主键

    /**
     * 获取数据实例
     * @return class
     */
    public function db()
    {

        return self::$db;
    }

    /**
     * 查询条件 (引用时重写)
     */
    public function where($data)
    {

        return self::$db
            ->when(@$data[self::$key], function ($q) use ($data) {
                $q->where(self::$key, $data[self::$key]);
            })
            ->when(@$data['guids'], function ($q) use ($data) {
                $q->whereIn(self::$key, $data['guids']);
            })
            ->when(@$data['status'], function ($q) use ($data) {
                $q->where('status', $data['status']);
            })
            ->when(@$data['app_id'], function ($q) use ($data) {
                $q->where('app_id', $data['app_id']);
            });
    }

    /**
     * 获取全部
     * @param $data
     * @return array
     */
    public function all($data)
    {

        return $this->where($data)->get();
    }

    /**
     * 获取列表
     * @param $data
     * @return array
     */
    public function list($data)
    {
        $current = $data['current'] ?? 1;
        $pageSize = $data['pageSize'] ?? 10;
        $order = $data['order'] ?? 'created_at';
        $by = $data['by'] ?? 'desc';

        // 查询条件
        $paginate = $this->where($data)
            ->orderBy($order, $by)
            ->paginate($pageSize, ['*'], 'page', $current);

        return [
            'current' => $current,
            'data' => $paginate->items(),
            'pageSize' => $pageSize,
            'total' => $paginate->total(),
        ];
    }

    /**
     * 状态更新
     * @param $guid
     * @param $data
     * @return int
     */
    public function status($guid, $status, $data = [])
    {

        $data['status'] = $status;

        return self::$db->where(self::$key, $guid)->update($data);
    }

    /**
     * 详情
     * @param $guid 
     * @return collection
     */
    public function info($guid)
    {

        return self::$db->where(self::$key, $guid)->first();
    }

    /**
     * 删除
     * @param $guid 
     * @return int
     */
    public function delete($guid)
    {

        return self::$db->where(self::$key, $guid)->delete();
    }
}
